<template>
	<view>
		<!--基础信息-->
		<view class="btName">基础信息</view>
		<view class="flex-white-plr26 ptb10 mt32 bdb_f5">
			<text class="mr26">入库单号</text>
			<u-input v-model="into_no" placeholder="为空时为系统自动生成" />
		</view>
		<view class="flex-white-plr26 ptb10 bdb_f5">
			<text class="mr26">入库单名称
				<text class="redXingh">*</text>
			</text>
			<u-input v-model="name" placeholder="请在此输入" />
		</view>
		<view class="flex-white-plr26 ptb20 bdb_f5" @click="selectWarehouseFun">
			<text class="mr26">仓库
				<text class="redXingh">*</text>
			</text>
			<view :class="store_name ? '' : 'cBlack'">
				{{store_name ? store_name : '请选择'}}
				<u-icon class="ml26" name="arrow-right" size="40" color="#888888"></u-icon>
			</view>
		</view>
		<view class="flex-white-plr26 ptb10 bdb_f5">
			<text class="mr26">总数量</text>
			<u-input v-model="number" type="number" input-align="right" placeholder="请输入或添加产品自动计算" />
		</view>
		<view class="flex-white-plr26 ptb10 bdb_f5">
			<text class="mr26">总金额</text>
			<u-input v-model="money" type="number" input-align="right" placeholder="请输入或添加产品自动计算" />
		</view>
		<view class="flex-white-plr26-column ptb20 mt32">
			<view style="margin-bottom: 8rpx;">
				<text>备注</text>
			</view>
			<u-input v-model="remark" type="textarea" :border="true" :height="100" :auto-height="true" />
		</view>

		<!--添加产品-->
		<view class="tjcpName">
			<text>添加产品</text>
		</view>
		<view class="productBox">
			<view class="myCard" v-if="cpList.length > 0">
				<view class="cardRow">
					<view>总数量：</view>
					<view>{{cpHzObj.totalNum}}</view>
				</view>
				<view class="cardRow">
					<view>价格合计：</view>
					<view>{{cpHzObj.skuSumPrice}}元</view>
				</view>
				<view class="cardRow">
					<view>总折扣%：</view>
					<view class="cpInput1">
						<u-input v-model="cpHzObj.discount_rate" type="number" height="50" :border="true"
							:clearable="false" placeholder="请输入" @input="cpzzkXgFun" />
					</view>

				</view>
				<view class="cardRow">
					<view>最终价格：</view>
					<view class="cpInput1">
						<u-input v-model="cpHzObj.saleSumPrice" type="number" height="50" :border="true"
							:clearable="false" placeholder="请输入" @input="cpzzPriceXgFun" />
					</view>
				</view>
			</view>
			<view class="myCard" v-for="(item, index) in cpList" :key="index">
				<u-icon name="close-circle-fill" size="50" class="clearIcon" color="#ff0000"
					@click="deleteCpFun(index)"></u-icon>
				<view class="cardTopName">产品名称：{{item.goods_name}}</view>
				<view class="disFlex">
					<view class="inputName">售价 (元)：</view>
					<view>
						<u-input v-model="item.price" type="number" height="50" :border="true" :clearable="false"
							placeholder="请输入" @input="cpDiscountUpdateFun(index, item)" />
					</view>
				</view>
				<view class="disFlex">
					<view class="inputName">税率 (%)：</view>
					<view class="cpInput">
						<u-input v-model="item.tax_rate" type="number" height="50" :border="true" :clearable="false"
							placeholder="请输入" @input="cpRateUpdateFun(index, item)" />
					</view>
					<view class="inputName">税金 (元)：</view>
					<view class="cpInput">
						<u-input v-model="item.tax_money" type="number" height="50" :border="true" :clearable="false"
							placeholder="请输入" @input="cpMoneyUpdateFun(index, item)" />
					</view>

				</view>
				<view class="disFlex">

					<view class="inputName">优惠 (%)：</view>
					<view class="cpInput">
						<u-input v-model="item.discount_rate" type="number" height="50" :border="true"
							:clearable="false" placeholder="请输入" @input="cpRateUpdateFun(index, item)" />
					</view>
					<view class="inputName">优惠金额：</view>
					<view class="cpInput">
						<u-input v-model="item.discount_money" type="number" height="50" :border="true"
							:clearable="false" placeholder="请输入" @input="cpMoneyUpdateFun(index, item)" />
					</view>
				</view>
				<view class="cardRow">
					<view>产品数量：</view>
					<view>
						<u-number-box v-model="item.num" :index="index" @change="cpCalcFun" :input-width="128"
							:input-height="60" :min="1" :max="100000"></u-number-box>
					</view>
				</view>
				<view class="cardRow">
					<view>价格合计：</view>
					<view class="greenPrice">￥{{item.totalPrice}}</view>
				</view>
			</view>
			<view class="addHKQS" @click="addChanPinFun">
				<text>点击添加相关产品</text>
				<u-icon name="plus-circle-fill" color="#007aff" size="56" style="margin-left: 16rpx;">
				</u-icon>
			</view>
		</view>
		<!--提交按钮-->
		<view class="submitView">
			<u-button type="primary" class="submitBtn" :ripple="true" ripple-bg-color="#909399" @click="submitBtnFun">
				{{pageType ? '保存' : '提交'}}</u-button>
		</view>
	</view>
</template>

<script>
	let that = '';
	import {
		getNowDate
	} from '@/utils/date.js'
	import {
		apiStockInto
	} from '@/api/crm.js'
	export default {
		data() {
			return {
				into_no: '',
				name: '',
				store_name: '',
				store_id: '',
				number: '',
				money: '',
				remark: '',
				into_user_name: '',
				into_user_id: '',
				cpList: [],
				cpHzObj: {},
				owner_user_id: uni.$userInfo.id,
				create_user_id: uni.$userInfo.id,
				xgInfoObj: {},
				pageType: ''
			}
		},
		onLoad(e) {
			that = this;
			if (e.type == 'update') {
				that.pageType = 'update';
				uni.setNavigationBarTitle({
					title: '修改入库单信息'
				})

				that.setDataFun();

			}
			uni.$on('chanpinBindFun', that.chanpinBindFun)
			uni.$on('stockStoreBindFun', that.stockStoreBindFun)
		},
		onBackPress() {
			uni.$off('chanpinBindFun', that.chanpinBindFun)
			uni.$off('stockStoreBindFun', that.stockStoreBindFun)
		},
		methods: {
			// 选择仓库
			selectWarehouseFun: function() {
				uni.navigateTo({
					url: '../stock_store/show?type=add_stockinto_goback'
				})
			},
			// 选择入库人员
			selectOperatorFun: function() {
				if (that.into_user_name) {
					that.into_user_id = uni.$userInfo.id;
					that.into_user_name = uni.$userInfo.real_name;
				} else {
					// 实际应用中这里可以选择其他人员
					that.into_user_id = uni.$userInfo.id;
					that.into_user_name = uni.$userInfo.real_name;
				}
			},
			// 添加相关产品
			addChanPinFun: function() {
				uni.navigateTo({
					url: '../goods_sku/show?type=stockinto'
				})
				that.isTjcp = true;
			},
			// 绑定产品
			chanpinBindFun: function(e) {
				let obj = {
					goods_id: e.goods_id,
					goods_name: e.goods_name,
					unit_name: e.unit_name,
					id: e.id,
					sku_id: e.id,
					sku_name: e.sku_name,
					price: e.sku_sale_price,
					discount_rate: 0,
					discount_money:0,
					tax_money:0,
					tax_rate:0,
					num: 1,
					totalPrice: e.sku_sale_price
				}
				if (that.isTjcp) {
					let arr = that.cpList;
					let isSave = false;
					for (var i = 0; i < arr.length; i++) {
						if (arr[i].id == obj.id) {
							isSave = true;
						}
					}
					if (!isSave) {
						arr = arr.concat(obj);
						that.cpList = arr;
						setTimeout(() => {
							uni.pageScrollTo({
								duration: 100,
								scrollTop: 100000
							})
						}, 88)
					} else {
						setTimeout(() => {
							uni.showToast({
								title: '该产品已存在！',
								icon: 'none',
								duration: 2000
							})
						}, 88)
					}
					that.isTjcp = false;
				}
				that.cpCalcFun();
			},
			// 删除产品
			deleteCpFun: function(iii) {
				let item = that.cpList[iii];
				that.cpList.splice(iii, 1)
				that.cpCalcFun();
			},
			// 税金率优惠率修改
			cpMoneyUpdateFun: function(iii, item) {
				let arr = that.cpList;
				// 税金额 = 税金/销售价格 × /100
				if (!item.tax_money) item.tax_money = 0
				item.tax_rate = (item.tax_money / item.price * 100 * item.num).toFixed(2);

				//优惠率 = 优惠金额/销售价格 × 100
				if (!item.discount_money) item.discount_money = 0
				item.discount_rate = (item.discount_money/item.price * 100* item.num).toFixed(2);


				that.$set(that.cpList, iii, item);

				that.cpCalcFun();
			},
			// 税金优惠金额修改
			cpRateUpdateFun: function(iii, item) {
				let arr = that.cpList;
				// 税率 = 销售价格 / 税金额 × 100
				if (!item.tax_rate) item.tax_rate = 0
				item.tax_money = (item.price * item.tax_rate / 100* item.num).toFixed(2);

				//优惠金额 = 销售价格 × 优惠率/100
				if (!item.discount_rate) item.discount_rate = 0
				item.discount_money = (item.price * item.discount_rate / 100* item.num).toFixed(2);

				that.$set(that.cpList, iii, item);
				that.cpCalcFun();
			},
			// 产品总折扣修改
			cpzzkXgFun: function() {
				// 销售价格 = 原价 × (1 - 折扣率/100)
				that.cpHzObj.saleSumPrice = (that.cpHzObj.skuSumPrice * (1 - that.cpHzObj.discount_rate / 100))
					.toFixed(2);
				that.money = that.cpHzObj.saleSumPrice;
			},
			// 产品最终价格修改
			cpzzPriceXgFun: function() {
				// 折扣率 = (1 - 销售价格/原价) × 100
				that.cpHzObj.discount_rate = ((1 - that.cpHzObj.saleSumPrice / that.cpHzObj.skuSumPrice) * 100)
					.toFixed(2);
				that.money = that.cpHzObj.saleSumPrice;
			},
			// 订单价格修改
			orderPriceXgFun: function() {
				if (that.cpList.length > 0) {
					that.cpHzObj.saleSumPrice = that.money;
					// 折扣率 = (1 - 销售价格/原价) × 100
					that.cpHzObj.discount_rate = ((1 - that.money / that.cpHzObj.skuSumPrice) * 100).toFixed(2);
				}
			},
		// 计算金额
		cpCalcFun: function() {
			let arr = that.cpList;
			let totalMoney = 0;
			let zprice = 0;
			let totalNum = 0;
			for (var i = 0; i < arr.length; i++) {

				// 计算单个产品的税金额和优惠金额（考虑数量因素）
				let tax_money = (arr[i].price * arr[i].num * (arr[i].tax_rate || 0) / 100);
				let discount_money = (arr[i].price * arr[i].num * (arr[i].discount_rate || 0) / 100);

				// 合计金额 = 销售价格 × 数量 + 税金额 - 优惠金额
				let totalPrice = (arr[i].price * arr[i].num) + tax_money - discount_money;

				arr[i].tax_money = tax_money.toFixed(2);
				arr[i].discount_money = discount_money.toFixed(2);
				arr[i].totalPrice = totalPrice.toFixed(2);
				totalMoney += totalPrice; //总销售金额
				zprice += parseFloat(arr[i].price) * parseFloat(arr[i].num); //总正价金额
				totalNum += parseFloat(arr[i].num); //总数据

			}
			that.cpHzObj.skuSumPrice = zprice.toFixed(2);

			// 如果折扣率为空，则默认折扣率为0
			if (!that.cpHzObj.discount_rate) that.cpHzObj.discount_rate = 0;

			//汇总的销售金额=总销售金额*折扣率
			that.cpHzObj.saleSumPrice = (totalMoney - (totalMoney * that.cpHzObj.discount_rate / 100)).toFixed(2); //汇总的销售金额
			that.cpHzObj.totalNum = totalNum; //汇总的数量
			that.cpList = arr;
			if (totalMoney == 0) {
				that.money = '';
			} else {
				that.money = totalMoney.toFixed(2);
			}

            that.number = that.cpHzObj.totalNum;

		},
			// 提交按钮方法
			submitBtnFun: function() {
				if (!that.name) {
					uni.$myModalFun('入库单名称不能为空，请输入！');
					return
				}
				if (!that.store_name) {
					uni.$myModalFun('仓库名称不能为空，请选择！');
					return
				}
				if (!that.money) {
					uni.$myModalFun('入库金额不能为空，请输入或者添加产品自动计算！');
					return
				}
				let req = {
					into_no: that.into_no,
					name: that.name,
					store_name: that.store_name,
					store_id: that.store_id,
					number: that.number,
					money: that.money,
					into_user_name: that.into_user_name,
					into_user_id: that.into_user_id,
					remark: that.remark,
					cpList: that.cpList,
					sys_user_id: that.owner_user_id,
					create_user_id: that.create_user_id,
					create_user_name: uni.$userInfo.real_name
				}
				if (that.cpList.length > 0) {
					req.cpHzObj = that.cpHzObj;
				}
					let reqObj = {
						cpList: that.cpList,
						req
					}
					let action = 'add';
					if (that.pageType == 'update') {
						action = 'update'
						reqObj.req.id = that.xgInfoObj.id;
						uni.showLoading({
							title: '修改中...'
						})
					} else {
						reqObj.req.create_user_id = that.create_user_id
						uni.showLoading({
							title: '提交中...'
						})
					}
					let reqData = {
						action: action,
						params: reqObj
					}
					apiStockInto(reqData)
						.then(res => {
						if (action == 'update') {
							uni.showToast({
								title: '入库单修改成功',
								icon: 'none',
								duration: 1000,
								mask: true
							})
							// 发送更新事件，通知详情页面刷新产品数据
							uni.$emit('updateStockIntoDetail', {
								id: that.xgInfoObj.id
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 1000)
							} else {
								uni.showToast({
									title: '入库单新增成功',
									icon: 'none',
									duration: 1000,
									mask: true
								})
								reqObj.req.id = res.data;
								uni.$emit('addStockIntoItemInListFun')
								setTimeout(() => {
									uni.redirectTo({
										url: './detail?index=0&fromDetail=true&id=' + res.data
									})
								}, 1000)
							}
						})
			},
			// 数据恢复
			setDataFun: function() {
				let obj = uni.$stockIntoInfo
				that.xgInfoObj = uni.$stockIntoInfo
				that.into_no = obj.into_no || obj.order_no
				that.name = obj.name
				that.store_name = obj.store_name 
				that.store_id = obj.store_id 
				that.number = obj.number 
				that.money = obj.money
				that.into_user_name = obj.into_user_name || uni.$userInfo.real_name
				that.into_user_id = obj.into_user_id || uni.$userInfo.id
				that.remark = obj.remark
				that.create_user_id = obj.create_user_id
				that.getCpByIdFun() //获得入库单产品列表明细
			},
			getCpByIdFun: function() {
				let reqData = {
					action: 'get_detail',
					params: {
						req: {
							id: that.xgInfoObj.id
						}
					}
				}
				uni.showLoading({
					title: '加载中...'
				})
				apiStockInto(reqData)
					.then(res => {
						let data = res.data.goods_list;
						if (data.length > 0) {
							let cpHzObj = {
								discount_rate: 0,
								skuSumPrice: 0,
								saleSumPrice: 0,
								totalNum: 0
							};
							for (var i = 0; i < data.length; i++) {
								var obj = data[i];
								obj.totalPrice =obj.last_money;
								obj.price = obj.price;
								obj.tax_rate=obj.tax_rate;
								obj.tax_money=obj.tax_money;
								data[i] = obj;
								cpHzObj.skuSumPrice += parseFloat(obj.last_money) ;
								cpHzObj.saleSumPrice += parseFloat(obj.last_money) ;
								cpHzObj.totalNum += parseFloat(obj.num);
							}
							cpHzObj.discount_rate = 0;
							that.cpHzObj = cpHzObj;
							that.cpList = data;
						}

						setTimeout(() => {
							uni.hideLoading()
						}, 888);

					})
			},
			// 绑定仓库
			stockStoreBindFun: function(e) {
				that.store_id = e.store_id;
				that.store_name = e.store_name;
			}
		}
	}
</script>

<style>
	page {
		background-color: #F8F8F8;
		padding-bottom: 260rpx;
	}

	.u-radio {
		width: 200rpx !important;
	}

	.submitView {
		width: 100%;
		padding: 16rpx 0 26rpx;
		background-color: #FFFFFF;
		position: fixed;
		bottom: 0;
		left: 0;
		border-top: 1rpx solid #f1f1f1;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
	}

	.submitBtn {
		width: 666rpx;
	}

	.productBox {
		background-color: #FFFFFF;
		margin-top: 32rpx;
		padding: 26rpx 0;
	}

	.tjcpName {
		width: 686rpx;
		height: 40rpx;
		font-size: 16px;
		font-weight: bold;
		border-left: 6rpx solid #007AFF;
		padding-left: 12rpx;
		margin-left: 26rpx;
		margin-top: 26rpx;
	}

	.cpInput {
		width: 150rpx !important;
		margin-right: 12rpx;
	}

	.clearIcon {
		position: absolute;
		right: 6rpx;
		top: 6rpx;
	}

	.greenPrice {
		font-size: 16px;
		color: #19BE6B !important;
		font-weight: bold;
	}

	.disFlex {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.inputName {
		color: #ADADAD;
		font-size: 16px;
	}

	.addHKQS {
		display: flex;
		align-items: center;
		padding: 16rpx 26rpx;
		font-size: 15px;
		font-weight: bold;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>